///////////////////////////////////////////////////////////////////////////////
//	FILENAME:	eTNote.m 
//	SUMMARY:	Implementation of a rtf note annotation
//	SUPERCLASS:	eTImage
//	INTERFACE:	None
//	PROTOCOLS:	<Tool, Annotation, ASCIISupport,InspectableTarget>
//	AUTHOR:		Rohit Khare
//	COPYRIGHT:	(c) 1994 California Institure of Technology, eText Project
///////////////////////////////////////////////////////////////////////////////
//	IMPLEMENTATION COMMENTS
//		Notes hold an RTF representation of some comments. ASCII conversion is
//  done as in eTDocInfo. Date is a last-modified string.
///////////////////////////////////////////////////////////////////////////////
//	HISTORY
//	10/30/94:	Modified to support <InspectableTarget>
//  07/27/94:	Still trying to tack down imag-loading bug,usd loadFromFile...
//  07/07/94:	Converted to imageAnnotation by RK and TRZ 
//  07/03/94:   HTMD Support by TRZ.
//  05/22/94:	Created. First actual implementation.
///////////////////////////////////////////////////////////////////////////////

#import "eTNote.h"
#define _eTNoteVERSION	10

NXAtom fileHack;

@implementation eTNote
+ toolAwake:theApp
{
	char        buf[MAXPATHLEN];
	NXBundle	*bundle;
	id			icon=nil;
	
	bundle = [NXBundle bundleForClass:[eTNote class]];
	if ([bundle getPath:buf forResource:"eTNoteIcon" ofType:"tiff"] ) {
		icon = [[NXImage alloc] initFromFile:buf];
		[icon setName:"eTNoteIcon"];
		if ([icon lockFocus]) [icon unlockFocus];
	} else {
		NXLogError("Image not found: eTNoteIcon");
	}
	[theApp   registerAnnotation: [eTNote class] 
							name: "Note"
					RTFDirective: "eTNote"
					   menuLabel: "Insert Note..."
						 menuKey: '\0'
						menuIcon: (NXImage *) icon];
	return self;
}


#define DEFAULTRTF "{\\rtf0\\ansi{\\fonttbl\\f1\\fnil Times-Roman;\\f2\\fswiss Helvetica;}\n\\margl40\n\\margr40\n\\pard\\tx520\\tx1060\\tx1600\\tx2120\\tx2660\\tx3200\\tx3720\\tx4260\\tx4800\\tx5320\\f1\\b0\\ulnone\\fs24\\fc0\\cf0 Rich-Text \n\\b comments\n\\b0  about this document\n}\n"
- init 
{
	[super init];
	[self setUsesButtonStyle:NO];
	[self setDraggable:YES];
	[self setImageComponent:[eTImageComponent newImageNamed:"etNoteIcon"]];

	RTFRep = (char *)malloc((strlen(DEFAULTRTF)+1)*sizeof(char));
	strcpy(RTFRep,DEFAULTRTF);
	return self;
}
- free
{
	free(RTFRep);
	return self = [super free];
}
- initFromPboard:thePB inDoc:theDoc linked:(BOOL) linked 
{
	struct	passwd *p;

	[super initFromPboard:thePB inDoc:theDoc linked:linked];
	//[self init];
	[imageComponent setDoc:theDoc];
	[etDoc registerNotification:self];	
	p = getpwuid(getuid());
	if (p->pw_name)
		strncpy(writer,p->pw_gecos,128);
	else strncpy(writer,"Author's Name",128);
	strncpy(date,[NXApp date],64);
	return self;
}
- drag: (Pasteboard *)draggingPboard image: (NXImage **)proxyImage
{
	char	 filename[MAXPATHLEN];
	NXStream *t;
	
	// write out .rtf file in /tmp
	sprintf(filename, "/tmp/eTNote.%d.rtf", [NXApp uniqueID]);

	[[eTNoteUI new] sync];
	t = NXOpenMemory(RTFRep, strlen(RTFRep), NX_READONLY);
	[theText readRichText:t];
	NXClose(t);
	[theText writeRTFtoPath:filename];
	
	[draggingPboard declareTypes:&NXFilenamePboardType num:1 owner:nil];
	[draggingPboard writeType: NXFilenamePboardType data: filename
					length: strlen(filename)];
	//NXLogError("NXImage got %x", [NXImage findImageNamed:NXUniqueString("eTNoteIcon")]);
	*proxyImage = [NXImage findImageNamed:NXUniqueString("eTNoteIcon")];
	//NXLogError("proxyImage got %x", *proxyImage);
	return self;
}
- inspect: (NXEvent*)e
{	[[NXApp inspector] inspect:self];
	return self;
}
- (id <Inspectable>) inspectableDelegate {
	return [[eTNoteUI new] setNote:self]; }

- readRichText:(NXStream *)stream forView:view 
{
	int i;
	
	NXScanf(stream, "%d ", &i);
	if (i != _eTNoteVERSION) {
		// bad version block.
	 NXLogError("eTNote found unparseable version %d at position %d",
					i, NXTell(stream));
		return nil;
	}
	
	NXScanf(stream, "%d", &i); NXGetc(stream); //space-eater
	if (i) NXRead(stream, writer, i);
	writer[i] = 0;
	
	NXScanf(stream, "%d", &i); NXGetc(stream); //space-eater
	if (i) NXRead(stream, date,i);
	date[i] = 0;

	NXScanf(stream, "%d", &i); NXGetc(stream); //space-eater
	if (i) {
		RTFRep = realloc(RTFRep,(i+1)*sizeof(char));
		NXRead(stream, RTFRep, i);
	}
	RTFRep[i]=0;
	NXGetc(stream); //trailing space
	[super	readRichText:stream forView:view];
	return self;
}

- writeRichText:(NXStream *)stream forView:view
{
	[[eTNoteUI new] sync];
	NXPrintf(stream, "%d %d %s %d %s %d %s ",
	 _eTNoteVERSION,strlen(writer),writer, strlen(date), date, strlen(RTFRep), RTFRep);
	return [super writeRichText:stream forView:view];
}

- writeASCIIRef:(NXStream *)stream forView:view
{
	NXStream *t;
	id aText = [NXApp sharedText];

	[[eTNoteUI new] sync];
	t = NXOpenMemory(RTFRep, strlen(RTFRep), NX_READONLY);
	[aText readRichText:t];
	NXClose(t);
	NXPrintf(stream, "%y made this comment, last modified on %s:\n", writer, date);
	[aText writeText:stream];
	NXPrintf(stream, "\n\t");
	[super writeASCIIRef:stream forView:view];
	return self;
}

- writeHTML:(NXStream *)stream forView:view
{
	char temp[MAXPATHLEN];
	char noteFile[MAXPATHLEN];	

	strcpy(temp, [[[view etDoc] docInfo] docPath]);
	*rindex(temp,'.')=0;
	sprintf(noteFile,"%s."HTMD_EXT"/eTNote.%x",temp,[NXApp uniqueID]); 
	NXPrintf(stream, "<A HREF=\"%V\">", noteFile);
	[super writeHTML:stream forView:view];
	NXPrintf(stream, "</A>");
	fileHack = NXUniqueString(noteFile);
	return self;
}
- writeLaTeX:(NXStream*)stream forView:view
{	
	char temp[MAXPATHLEN];
	char noteFile[MAXPATHLEN];	

	[super writeLaTeX:stream forView:view];
	strcpy(temp, [[[view etDoc] docInfo] docPath]);
	*rindex(temp,'.')=0;
	sprintf(noteFile,"%s."HTMD_EXT"/eTNote.%x",temp,[NXApp uniqueID]); 
	NXPrintf(stream, "\footnote{See the file %w for a comment by %w on %w", noteFile,writer,date);
	fileHack = NXUniqueString(noteFile);
	return self;
}

- writeComponentToPath:(char *)thePath inFormat:(int)fmt 
{
	char 		temp[MAXPATHLEN];
	char		noteFile[MAXPATHLEN];
	id		 	aText;
	NXStream	*t;
	NXRect		rect;

	if(!etDoc)	NXLogError("etDoc is nil at %s %u",__FILE__,__LINE__);

	[super writeComponentToPath:thePath inFormat:fmt];

	if(fmt==HTMD_FMT || fmt==TeXD_FMT) {
		aText = [[eText alloc] init];
		rect.origin.x = rect.origin.y = 0;
		rect.size.height = rect.size.width = MAXFLOAT;
		[aText initFrame:&rect];
		t = NXOpenMemory(RTFRep, strlen(RTFRep), NX_READONLY);
		[aText readRichText:t];
		NXClose(t);
		[aText setSel:0:0];
		
		sprintf(noteFile, "%s made this comment, last modified on %s:\n", writer, date);
		[aText replaceSel:noteFile];
		
		t = NXOpenMemory(NULL, 0, NX_READWRITE);
		if(fmt==HTMD_FMT) 	[aText writeHTML:t withTags:NULL];
		if(fmt==TeXD_FMT)	[aText writeLaTeX:t	withTags: NULL];
		aText = [aText free];
		sprintf(temp,"%s/%s",thePath,fileHack);
		NXSaveToFile(t,temp);
		NXCloseMemory(t,NX_FREEBUFFER);
	}
	return self;
}

- setRTFRep:(const char *)newRep 
{
	RTFRep = realloc(RTFRep,strlen(newRep));
	strcpy(RTFRep,newRep); 
	strncpy(date,[NXApp date],64); 
	return self;
}


- (const char *)RTFRep {return RTFRep;}
- (const char *)owner{return writer;}
- setOwner:(const char *)newOwner{strncpy(writer,newOwner,128); return self;}
- (const char *)date{return date;}
@end